package com.hairline.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hairline.bean.Collect;
import com.hairline.bean.CollectExample;
import com.hairline.bean.vo.WxCollectListVO;
import com.hairline.mapper.CollectMapper;
import com.hairline.mapper.WxCollectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxCollectServiceImpl implements WxCollectService {
    @Autowired
    WxCollectMapper wxCollectMapper;
    @Autowired
    CollectMapper collectMapper;

    @Override
    public Map<String, Object> collectList(HashMap<String, Integer> map) {
        PageHelper.startPage((map.get("page")), map.get("size"));
        Integer type = map.get("type");
        Integer userId = map.get("userId");
        List<WxCollectListVO> list = wxCollectMapper.selectCollectList(type, userId);
//        PageInfo<WxCollectListVO> info = new PageInfo<>();
        PageInfo info = new PageInfo(list);
        long total = info.getPages();
        Map<String, Object> result = new HashMap<>();
        result.put("totalPages", total);
        result.put("collectList", list);
        return result;
    }

    @Override
    public Map<String, String> addOrDelete(Byte type, Integer valueId, Integer userId) {
        Map<String, String> result = new HashMap<>();
        //查询当前用户是否收藏当前商品
        CollectExample collectExample = new CollectExample();
        CollectExample.Criteria criteria = collectExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andValueIdEqualTo(valueId);
        List<Collect> collects = collectMapper.selectByExample(collectExample);
        //如果查询没有结果，表示还未在表中添加该商品，需要插入一条新数据
        if (collects.size() == 0) {
            Collect newCollect = new Collect(null, userId, valueId, type, new Date(), new Date(), false);
            collectMapper.insert(newCollect);
            result.put("type", "add");
            return result;
        }
        Collect oldCollect = collects.get(0);
        Boolean oldDeleted = oldCollect.getDeleted();
        Collect newCollect = new Collect();
        //为更新的collect对象提供参数
        newCollect.setId(oldCollect.getId());
        newCollect.setUpdateTime(new Date());
        //oldDeleted为true,当前商品已添加且当前状态为被删除，需要更新状态为正常
        if (oldDeleted) {
            newCollect.setDeleted(false);
            result.put("type", "add");
        }
        //deleted为false,一天假且当前状态为正常,需要更新状态为删除
        else {
            newCollect.setDeleted(true);
            result.put("type", "delete");
        }
        collectMapper.updateByPrimaryKeySelective(newCollect);
        return result;
    }
}
